package com.shanghaionstar.activity.webview.handler;

import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.webkit.WebView;

import com.onstar.cn.common.jsBridge.BridgeHandler;
import com.onstar.cn.common.jsBridge.BridgeWebView;
import com.onstar.cn.common.jsBridge.CallBackFunction;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.shanghaionstar.activity.WithActionSheetHelper;

import java.util.Map;

/**
 * Created by Rengui Lu on 2017/3/3.
 */
public class UploadImgWebHandler extends DefaultWebHandler {
    private WithActionSheetHelper helper;

    public UploadImgWebHandler(Context context) {
        super(context);
        helper = new WithActionSheetHelper((BaseActivity) context);
    }

    @Override
    public void handMsg(Message msg) {
        switch (msg.what) {
            case IWebType.TYPE_UPLOAD_IMG:
                init(msg);
                break;
            case IWebType.TYPE_ON_ACTIVITY_RESULT:
                callBack(msg);
                break;
        }
    }

    private void callBack(Message msg) {
        CommonWebViewActivity mActivity;
        if (context instanceof CommonWebViewActivity) {
            mActivity = (CommonWebViewActivity) context;
            helper.onActivityResult(msg.arg1, msg.arg2, (Intent) msg.obj);
            WebView webview = mActivity.getWebview();
            ((BridgeWebView) webview).callHandler("resultCamera", "www.baidu.com", null);
        }
    }

    private void init(Message msg) {
        CommonWebViewActivity mActivity;
        if (context instanceof CommonWebViewActivity) {
            mActivity = (CommonWebViewActivity) context;
            WebView webview = mActivity.getWebview();
            String linkUrl = ((WebDataEntity) msg.obj).getLinkUrl();
            Map<String, String> header = mActivity.getExtraHeaders();
            webview.loadUrl(linkUrl,header);
            register(webview);
        }
    }


    public void register(final WebView webview) {
        if(webview instanceof BridgeWebView) {
            ((BridgeWebView) webview).registerHandler("openCamera", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
//                    H5JSObject h5JSObject = new H5JSObject(context);
//                    h5JSObject.setWebView((BridgeWebView)webview);
//                    h5JSObject.openCamera();
                    helper.showDialogToTakeChoosePicture();
                }
            });
        }
    }

}
